/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package Vista;

import Controlador.ControlCliente;
import Controlador.ControlCotizacion;
import Controlador.ControlImagen;
import Modelo.Cotizacion;
import Modelo.Imagen;
import java.awt.Color;
import java.awt.Desktop;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRExporter;
import net.sf.jasperreports.engine.JRExporterParameter;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.export.JRPdfExporter;
import net.sf.jasperreports.engine.export.ooxml.JRDocxExporter;
import net.sf.jasperreports.engine.util.JRLoader;
import org.jdesktop.swingx.painter.MattePainter;
import org.jdesktop.swingx.util.PaintUtils;

/**
 *
 * @author Damian
 */
public class PnlExportar extends javax.swing.JPanel {

    /**
     * Creates new form PnlExportar
     */
    private JasperReport reporte;
    private JasperPrint print;
    Cotizacion cotActual;

    public PnlExportar(Cotizacion cotActual) {
        initComponents();
        this.cotActual = cotActual;
        jXPanel1.setBackgroundPainter((new MattePainter(PaintUtils.BLUE_EXPERIENCE, true)));

        lblEspera.getBusyPainter().setHighlightColor(new Color(44, 61, 146).darker());
        lblEspera.getBusyPainter().setBaseColor(new Color(168, 204, 241).brighter());
        lblEspera.setBusy(false);

        cmbFormato.addItemListener(new ItemListener() {

            @Override
            public void itemStateChanged(ItemEvent e) {
                if (e.getStateChange() == 1) {
                    String ulti = "";
                    ulti = txtNombre.getText().substring(txtNombre.getText().length() - 4);
                    ulti = ulti.toLowerCase();
                    System.out.println("ulti: " + ulti);
                    if (cmbFormato.getSelectedIndex() == 0) {
                        if (ulti.equals("docx")) {
                            txtNombre.setText(
                                    txtNombre.getText().substring(0, txtNombre.getText().length() - 5));

                        }
                        if (!ulti.equals(".pdf")) {
                            txtNombre.setText(txtNombre.getText() + ".pdf");
                        }
                    } else {
                        if (ulti.equals(".pdf")) {
                            txtNombre.setText(
                                    txtNombre.getText().substring(0, txtNombre.getText().length() - 4));

                        }
                        if (!ulti.equals("docx")) {
                            txtNombre.setText(txtNombre.getText() + ".docx");

                        }
                    }
                }
            }
        });
        lblEspera.setText("Esperando...");
    }

    public Cotizacion getCotActual() {
        return cotActual;
    }

    public void setCotActual(Cotizacion cotActual) {
        this.cotActual = cotActual;
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel2 = new javax.swing.JPanel();
        btnExportar = new javax.swing.JButton();
        btnAbrir = new javax.swing.JButton();
        jXPanel1 = new org.jdesktop.swingx.JXPanel();
        lblEspera = new org.jdesktop.swingx.JXBusyLabel();
        txtlDir = new javax.swing.JTextField();
        txtNombre = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        btnSeleccionar = new javax.swing.JButton();
        cmbFormato = new javax.swing.JComboBox();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();

        setLayout(new java.awt.BorderLayout());

        btnExportar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Vista/Iconos/document-save-as.png"))); // NOI18N
        btnExportar.setText("Exportar");
        btnExportar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnExportarActionPerformed(evt);
            }
        });
        jPanel2.add(btnExportar);

        btnAbrir.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Vista/Iconos/application-pdf.png"))); // NOI18N
        btnAbrir.setText("Abrir");
        btnAbrir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAbrirActionPerformed(evt);
            }
        });
        jPanel2.add(btnAbrir);

        add(jPanel2, java.awt.BorderLayout.SOUTH);

        lblEspera.setText("Esperando...");

        txtlDir.setText("./");
        txtlDir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtlDirActionPerformed(evt);
            }
        });

        txtNombre.setText("Cotizacion.pdf");

        jLabel1.setText("Dirección: ");

        btnSeleccionar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Vista/Iconos/document-open.png"))); // NOI18N
        btnSeleccionar.setText("Seleccionar");
        btnSeleccionar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSeleccionarActionPerformed(evt);
            }
        });

        cmbFormato.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "PDF", "DOC" }));

        jLabel2.setText("Nombre del archivo:");

        jLabel3.setText("Formato:");

        javax.swing.GroupLayout jXPanel1Layout = new javax.swing.GroupLayout(jXPanel1);
        jXPanel1.setLayout(jXPanel1Layout);
        jXPanel1Layout.setHorizontalGroup(
            jXPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jXPanel1Layout.createSequentialGroup()
                .addGroup(jXPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jXPanel1Layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(jXPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel2)
                            .addComponent(jLabel1))
                        .addGap(18, 18, 18)
                        .addGroup(jXPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jXPanel1Layout.createSequentialGroup()
                                .addComponent(txtlDir, javax.swing.GroupLayout.PREFERRED_SIZE, 283, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(btnSeleccionar))
                            .addGroup(jXPanel1Layout.createSequentialGroup()
                                .addComponent(txtNombre, javax.swing.GroupLayout.PREFERRED_SIZE, 149, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(41, 41, 41)
                                .addComponent(jLabel3)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(cmbFormato, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
                    .addGroup(jXPanel1Layout.createSequentialGroup()
                        .addGap(233, 233, 233)
                        .addComponent(lblEspera, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jXPanel1Layout.setVerticalGroup(
            jXPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jXPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jXPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(txtNombre, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3)
                    .addComponent(cmbFormato, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jXPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(txtlDir, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnSeleccionar))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(lblEspera, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(227, Short.MAX_VALUE))
        );

        add(jXPanel1, java.awt.BorderLayout.CENTER);
    }// </editor-fold>//GEN-END:initComponents

    public void entregar() {
        try {
            cotActual.setEstado(true);
            new ControlCotizacion().actualizar(cotActual);
        } catch (SQLException ex) {
            ex.printStackTrace();
        }
    }
    private void btnExportarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnExportarActionPerformed

        if (cotActual != null) {
            if (cotActual.getCodigo() > 0) {
                Runnable hilo = new Runnable() {

                    @Override
                    public void run() {
                        lblEspera.setText("Generando la cotización.");
                        lblEspera.setBusy(true);
                        try {
                            Connection cn = new ControlCliente().conectar();
                            HashMap<String, Object> params = new HashMap<>();
                            params.put("codigo_cotizacion", cotActual.getCodigo());
                            guardarImg();
                            entregar();

                            String ruta = txtlDir.getText() + File.separator + txtNombre.getText();
                            System.out.println("Exportando cotización a " + ruta);
                            Boolean isPDF = true;
                            if (cmbFormato.getSelectedIndex() == 0) {
                                isPDF = true;
                            } else {
                                isPDF = false;
                            }
                            jasperReport(ruta, params, cn, isPDF);
                            lblEspera.setBusy(false);

                        } catch (Exception ex) {
                            ex.printStackTrace();
                        }
                        System.out.println("acabo el hilo");
                    }
                };
                Thread h = new Thread(hilo);
                h.start();
            } else {
                JOptionPane.showMessageDialog(this, "Cotización Inválida");
                System.out.println("Codigo de contizacion invalido");
            }
        } else {
            JOptionPane.showMessageDialog(this, "Cotización Inválida.");
            System.out.println("cotizacion nula");
        }

    }//GEN-LAST:event_btnExportarActionPerformed

    public boolean jasperReport(String ruta, Map<String, Object> params, Connection conn, boolean pdf) throws ClassNotFoundException, JRException {
        try {

            JasperReport report = (JasperReport) JRLoader.loadObject(new File("report1.jasper"));
            JasperPrint jasperPrint = JasperFillManager.fillReport(report, params, conn);
            if (pdf) {
                JRExporter exporter = new JRPdfExporter();
                exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
                exporter.setParameter(JRExporterParameter.OUTPUT_FILE, new java.io.File(ruta));
                exporter.exportReport();

            } else {
                JRDocxExporter exp = new JRDocxExporter();
                exp.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
                exp.setParameter(JRExporterParameter.OUTPUT_FILE, new java.io.File(ruta));
                exp.exportReport();
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return true;
    }

    public static BufferedImage toBufferedImage(Image img) {
        int width = img.getWidth(null);
        int height = img.getHeight(null);
        BufferedImage bi = new BufferedImage(width, height, BufferedImage.TRANSLUCENT);
        Graphics g = bi.getGraphics();
        g.drawImage(img, 0, 0, null);
        g.dispose();
        return bi;
    }

    public void guardarImg() {
        try {
            if (new File("./img").isDirectory() == false) {

            }
            ArrayList<Imagen> listaImg = new ControlImagen().getImagenes();
            for (int i = 0; i < listaImg.size(); i++) {
                Imagen imagen = listaImg.get(i);
                String formato = imagen.getNombre().substring(imagen.getNombre().length() - 3);
                File archivo = new File("./img/" + imagen.getNombre());

                System.out.println(archivo.createNewFile());
                ImageIO.write(toBufferedImage(imagen.getImagen()),
                        formato, archivo);
            }

        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
    private void btnSeleccionarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSeleccionarActionPerformed
        JFileChooser fc = new JFileChooser();
        fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        int opc = fc.showOpenDialog(this);
        if (opc == JFileChooser.APPROVE_OPTION) {
            txtlDir.setText(fc.getSelectedFile().getAbsolutePath());
        }
    }//GEN-LAST:event_btnSeleccionarActionPerformed

    private void txtlDirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtlDirActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_txtlDirActionPerformed

    private void btnAbrirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAbrirActionPerformed
        // TODO add your handling code here:
        try {
            String ruta = txtlDir.getText() + File.separator + txtNombre.getText();
            File file = new File(ruta);
            Desktop.getDesktop().open(file);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }//GEN-LAST:event_btnAbrirActionPerformed


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAbrir;
    private javax.swing.JButton btnExportar;
    private javax.swing.JButton btnSeleccionar;
    private javax.swing.JComboBox cmbFormato;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JPanel jPanel2;
    private org.jdesktop.swingx.JXPanel jXPanel1;
    private org.jdesktop.swingx.JXBusyLabel lblEspera;
    private javax.swing.JTextField txtNombre;
    private javax.swing.JTextField txtlDir;
    // End of variables declaration//GEN-END:variables
}
